import axios, { AxiosInstance, AxiosRequestConfig } from 'axios'
import { ElMessage } from 'element-plus'
import type { ApiResponse } from '../model/common-model'

// API 前缀，默认 '/api'，可通过环境变量 VITE_API_PREFIX 覆盖（例如 '/api/v1'）
const apiPrefix = (import.meta as any).env?.VITE_API_PREFIX || '/api'

// 创建axios实例
const service: AxiosInstance = axios.create({
  baseURL: apiPrefix, // 所有请求都带上前缀
  timeout: 15000
})

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 从 localStorage 获取令牌并设置请求头
    const token = localStorage.getItem('access_token') || localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器 - 适配文档中的API响应格式
service.interceptors.response.use(
  (response) => {
    const res = response.data as ApiResponse<any>
    
    // 处理响应，根据文档，code=0表示成功，其他值表示错误
    if (res.code !== 0) {
      ElMessage.error(res.errorMsg || '请求失败')
      return Promise.reject(new Error(res.errorMsg || '请求失败'))
    }
    // 返回响应数据，解决类型问题
    return Promise.resolve(res) as any
  },
  (error) => {
    // 检查是否为登录请求
    const isLoginRequest = error.config && (
      error.config.url.includes('/auth/login') || 
      error.config.url.includes('/login')
    );
    
    // 处理401错误
    if (error.response && error.response.status === 401) {
      // 如果是登录请求本身的401，则直接将错误传递给组件处理
      if (isLoginRequest) {
        console.log('登录失败：用户名或密码错误')
        // 确保错误信息从响应中提取
        try {
          const errorData = error.response.data;
          const errorMessage = errorData.errorMsg || '用户名或密码不正确';
          return Promise.reject(new Error(errorMessage));
        } catch (e) {
          return Promise.reject(new Error('用户名或密码不正确'));
        }
      }
      
      // 其他非登录请求的401错误，重定向到登录页
      console.log('检测到401未授权错误，正在跳转到登录页...')
      // 清除token和用户信息
      localStorage.removeItem('token')
      localStorage.removeItem('access_token')
      localStorage.removeItem('userInfo')
      
      // 获取当前路径，用于登录后重定向
      const currentPath = window.location.pathname
      
      // 跳转到登录页
      window.location.href = `/login?redirect=${currentPath}`
      
      // 返回一个已解决的Promise，避免显示错误消息
      return Promise.resolve({ code: 401, data: null, errorMsg: '未授权，请重新登录' } as ApiResponse<any>)
    }
    
    // 处理其他错误
    const message = error.response?.data?.errorMsg || error.message || '请求失败'
    ElMessage.error(message)
    return Promise.reject(error)
  }
)

// 封装GET请求
export function get<T = any>(url: string, params?: any, config?: AxiosRequestConfig): Promise<ApiResponse<T>> {
  return service.get(url, { params, ...config }) as unknown as Promise<ApiResponse<T>>
}

// 封装POST请求
export function post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<ApiResponse<T>> {
  return service.post(url, data, config) as unknown as Promise<ApiResponse<T>>
}

// 封装PUT请求
export function put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<ApiResponse<T>> {
  return service.put(url, data, config) as unknown as Promise<ApiResponse<T>>
}

// 封装DELETE请求
export function del<T = any>(url: string, params?: any, config?: AxiosRequestConfig): Promise<ApiResponse<T>> {
  return service.delete(url, { params, ...config }) as unknown as Promise<ApiResponse<T>>
}

export default service
